package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserMapper;
import com.atguigu.gmall.user.service.UserServcie;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements UserServcie {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Map<String, String> login(UserInfo userInfo, HttpServletRequest request) throws JsonProcessingException {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name",userInfo.getLoginName());
        String encrypt = MD5.encrypt(userInfo.getPasswd());
        wrapper.eq("passwd",encrypt);
        UserInfo info = userMapper.selectOne(wrapper);
        if (info != null){
            Map<String, String> map = new HashMap<>();
            String token = UUID.randomUUID().toString().replace("-", "");
            map.put("token",token);
            map.put("nickName",info.getNickName());

            //登陆成功
            ObjectMapper mapper = new ObjectMapper();
            //redis中保存用户id ip地址
            Map<String, Object> redisUser = new HashMap<>();
            redisUser.put("userId",info.getId());
            //拿到ip地址
            String ipAddress = IpUtil.getIpAddress(request);
            redisUser.put("ipAddr", ipAddress);
            redisUser.put("userInfo",info);

            //订单,物流都需要当前登陆的用户的用户id
            String json = mapper.writeValueAsString(redisUser);

            //给redis中保寸登陆成功的用户信息
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token, json,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            
            return map;
        }else {
            return null;
        }
    }

    @Override
    public void logout(String token) {

        String key = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(key);
    }
}
